package main

import (
    "os"
    "io"
    "bufio"
    "bytes"
    "fmt"
    "strconv"
    "ygo"
)

//import "memory"

func readLines(path string) (lines []string, err error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 1024))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == io.EOF {
        err = nil
    }
    return
}

func main() {

  var vdata int
  var nb_line int

  load := make(chan int)
  pc_addr := make(chan int)
  instruction := make(chan int)
  ls_addr := make(chan int)
  ls_rw := make(chan bool)
  ls_data_in := make(chan int)
  ls_data_out := make(chan int)

  go ygo.Memory ( load, pc_addr, instruction, ls_addr, ls_rw, ls_data_in, ls_data_out)

  fmt.Println("Reading file foo.txt")

  lines, err := readLines("foo.txt")
  if err != nil {
      fmt.Println("Error: %s\n", err)
      return
  }

  fmt.Println("PC_RETURN = ", ygo.PC_RETURN)

  nb_line = 0
  for _, line := range lines {
      if (nb_line == 0) {
        fmt.Println(line)
      } else {
        vdata,err = strconv.Atoi(line)
        load <- vdata
      }
      nb_line = nb_line + 1
  }
  close(load)

  fmt.Println("Trying some reads now")
  pc_addr <- 1
  vdata = <-instruction
  fmt.Println("Read ", vdata, " from address 1")
  pc_addr <- 5
  vdata = <-instruction
  fmt.Println("Read ", vdata, " from address 5")
  pc_addr <- 18
  vdata = <-instruction
  fmt.Println("Read ", vdata, " from address 18")
}

